package com.mos.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;

/**
 *
 */
public class TreeUtil {

    public static List tree(List data, String idKey, String pidKey, String textKey) {
        if (null == data || 0 == data.size()) return null;

        List nodes = new ArrayList();
        for (Object o : data) {
            Map node = convertModelToMap(o);
            node.put("id", node.get(idKey));
            node.put("name", node.get(textKey));
            node.put("path", node.get("path"));
            nodes.add(node);
        }

        //1、若只有一个节点数据，则直接返回
        if (2 > nodes.size()) return nodes;

        //2、若节点无父子关系，则直接返回
        if (null == pidKey || "".equals(pidKey)) return nodes;

        //3、存在父子关系，那么计算出最顶层节点返回
        //3.1、分组
        Map groups = groupByPid(nodes, pidKey);
        //3.2、分组失败直接返回
        if (null == groups) return nodes;
        //3.3、筛选最顶层节点
        List delnodes = new ArrayList();
        for (int i = 0; i < nodes.size(); i++) {
            Map node = (Map) nodes.get(i);
            String id = node.get(idKey).toString();
            List children = (List) groups.get(id);
            if (null != children && 0 < children.size()) {
                node.put("children", children);
                delnodes.addAll(children);
            }
        }
        nodes.removeAll(delnodes);

        return nodes;
    }

    //根据pid 分组
    private static Map groupByPid(List nodes, String pidKey) {
        if (null == nodes || 0 == nodes.size()) return null;
        if (null == pidKey || "".equals(pidKey)) return null;

        Map groups = new HashMap();
        for (int i = 0; i < nodes.size(); i++) {
            Map node = (Map) nodes.get(i);

            Object pid = node.get(pidKey);
            if (groups.get(pid) == null) {
                List l1 = new ArrayList();
                groups.put(pid, l1);
                l1.add(node);
            } else {
                List l2 = (List) groups.get(pid);
                l2.add(node);
            }
        }
        return groups;
    }


    //model-->map
    //注意属性值为null将忽略此属性，为""则不会忽略
    private static Map convertModelToMap(Object o) {
        String jsonStr = JSON.toJSONString(o);
        Map m = JSON.parseObject(jsonStr.toString(), Map.class);
        return m;
    }

}
